<template>
  <main-card-admin title="公开模型" :loading="globalLoading" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button v-auth="'admin-model-manage-create'" type="primary" @click="handleEdit('add')">新建</a-button>
    </template>
    <template #screen-space>
      <a-row class="page-top" :wrap="false">
        <a-col>
          <a-select
            ref="select"
            v-model:value="pageForm.labelIds"
            class="w-140"
            :options="statusOptions"
            :field-names="{ label: 'labelName', value: 'labelIds' }"
            @change="getDataList()"
          />
        </a-col>
        <a-col flex="1" />
        <a-col>
          <a-input
            v-model:value="pageForm.modelName"
            allow-clear
            placeholder="请输入名称"
            class="w-328"
            @press-enter="getDataList({ offset: 1 })"
          >
            <template #prefix><SearchOutlined /></template>
          </a-input>
        </a-col>
      </a-row>
    </template>
    <div class="search-table">
      <div class="list-table">
        <a-table
          :style="{ width: '100%' }"
          :columns="tableColumns"
          :data-source="caseList"
          :pagination="false"
          :row-key="(r:RecordListItem) => r.id"
          class="header-right-angle admin-table"
          @change="onTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'commonModelLabelVOList'">
              <label-classification :label-list="record.commonModelLabelVOList" />
            </template>

            <template v-else-if="column.dataIndex == 'createTime'">
              <div>
                {{ dateFormat(record.createTime) }}
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'updateTime'">
              <div>
                {{ dateFormat(record.updateTime) }}
              </div>
            </template>
            <template v-else-if="column.dataIndex == 'tools'">
              <a-button type="link" style="margin-right: 12px" @click.stop="handleToDetail(record as RecordListItem)">详情</a-button>

              <a-dropdown v-if="checkKey(['admin-model-manage-edit', 'admin-model-manage-delete'])" placement="bottomRight" @click.stop>
                <a-button type="text" class="icon-only-btn" @click.stop>
                  <i class="iconfont icon-more-line"></i>
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-if="checkKey('admin-model-manage-edit')"
                      class="menu-icon-item"
                      @click="handleEdit('edit', record as RecordListItem)"
                    >
                      编辑
                    </a-menu-item>
                    <a-menu-item
                      v-if="checkKey('admin-model-manage-delete')"
                      class="menu-icon-item"
                      @click="handleDelete(record as RecordListItem)"
                    >
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
            <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
          </template>
        </a-table>
        <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
      </div>
    </div>
  </main-card-admin>
  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    :msg="`已有${currentCollection}人收藏此模型，请确认是否删除？`"
    :label="`请输入模型名称`"
    :loading="confirmLoading"
    :confirm-name="currentDeleteTaskItem?.modelName"
    @ok="onOkDeleteTask"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { computed, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import LabelClassification from '@/components/LabelClassification/index.vue'
  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import { checkKey } from '@/directives/auth'
  import useList from '@/hooks/use-list'
  import { adminCollectionApi, adminModelManageApi, tagManageApi } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'

  import { DictionaryType, PageForm, RecordListItem, TaskStatus } from '../types'
  type SorterType = 'desc' | 'asc'
  const router = useRouter()
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'modelName',
        width: 180
      },
      {
        title: '标签',
        dataIndex: 'commonModelLabelVOList',
        width: 380
      },

      {
        title: '描述',
        dataIndex: 'description'
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 180,
        isSort: true
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        width: 180,
        isSort: true
      },
      {
        title: '',
        width: 98,
        dataIndex: 'tools'
      }
    ])
  )
  /********************分类************************/

  let statusOptions = ref<TaskStatus[]>([
    {
      labelName: '全部标签',
      labelIds: ''
    }
  ])

  //表格
  const {
    pageForm,
    loading,
    dataList: caseList,
    getDataList
  } = useList<PageForm, RecordListItem>(adminModelManageApi.list, {
    modelName: '',
    labelIds: '',
    columns: 'createTime',
    order: 'desc'
  })
  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    let columns = sorter.field
    let order = sorter.order === 'ascend' ? 'asc' : ('desc' as SorterType)
    if (!sorter.order) {
      columns = 'createTime'
      sorter.order = 'desc'
    }
    getDataList({ offset: 1, order, columns })
  }

  //获取字典信息
  const { loading: getDictionLoading, runAsync: getDictionaryRun } = useRequest<ResponseData<DictionaryType[]>>(tagManageApi.list, {
    onSuccess: ({ data }) => {
      statusOptions.value = [
        ...statusOptions.value,
        ...data.map((item: DictionaryType) => ({ labelName: item.v, labelIds: item.id }))
      ] as TaskStatus[]
    }
  })
  //全局Loading
  const globalLoading = computed(() => {
    return loading.value || getDictionLoading.value
  })
  /********************跳转************************/
  const handleToDetail = (r: RecordListItem) => {
    // window.open(`/item-case/detail/${r.id}`)
    let url = `/model-base/list/public-model/public-model-datail/${r.id}`
    window.open(url, '_blank')
  }

  // 删除模型
  const currentDeleteTaskItem = ref<RecordListItem>()
  const isDeleteDialogShow = ref(false)
  const FAVORITE_TYPE_CASE = 4 //代表收藏类型为模型
  const handleDelete = (item: RecordListItem) => {
    currentDeleteTaskItem.value = item
    getCollectionRun({
      favoriteType: FAVORITE_TYPE_CASE,
      objectId: item.id
    })
    isDeleteDialogShow.value = true
  }
  const { loading: confirmLoading, runAsync: runAdminModelManage } = useRequest(adminModelManageApi.del)
  const onOkDeleteTask = async () => {
    await runAdminModelManage({}, { urlParams: { id: currentDeleteTaskItem.value?.id || '' }, isAddUid: true })
    message.success('删除成功')
    isDeleteDialogShow.value = false
    getDataList()
  }
  //查询模型收藏人数
  const currentCollection = ref(0)
  const { runAsync: getCollectionRun } = useRequest<ResponseData<number>>(adminCollectionApi.numberOfCollections, {
    onSuccess: ({ data }) => {
      currentCollection.value = data
    }
  })

  //新建

  const handleEdit = (type: 'add' | 'edit', item?: RecordListItem) => {
    // console.log(type, item.id)

    if (type === 'add') {
      router.push(`/admin/model-manage/add`)
      return
    }
    router.push(`/admin/model-manage/edit/${item?.id}`)
  }
  getDataList()
  getDictionaryRun({
    type: 'common_model'
  })
</script>
